<template>
  <div class="knowledge-base-management-container">
    <!-- 知识库统计 -->
    <div class="stats">
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ knowledgeStats.totalDocuments }}</div>
          <div class="stat-label">总文档数</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ knowledgeStats.totalVectorCount }}</div>
          <div class="stat-label">向量数量</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ formatFileSize(knowledgeStats.totalStorageSize) }}</div>
          <div class="stat-label">存储大小</div>
        </div>
      </el-card>
    </div>

    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>知识库管理</span>
          <el-button type="primary" :icon="Plus" @click="showCreateDialog">新建知识库</el-button>
        </div>
      </template>

      <el-table :data="knowledgeBases" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="知识库名称" width="180" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button size="small" @click="viewKnowledgeBaseDocuments(scope.row.id)">管理文档</el-button>
            <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteKnowledgeBase(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新建/编辑知识库对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑知识库' : '新建知识库'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="kbFormRef"
        :model="currentKnowledgeBase"
        :rules="kbRules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="currentKnowledgeBase.name" placeholder="请输入知识库名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="currentKnowledgeBase.description"
            type="textarea"
            :rows="3"
            placeholder="请输入知识库描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEditMode ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/utils/api'

const router = useRouter()

const knowledgeBases = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEditMode = ref(false)
const currentKnowledgeBase = reactive({
  id: null,
  name: '',
  description: '',
  userId: 1 // 假设当前用户ID为1，实际应从登录信息获取
})
const kbFormRef = ref()

// 知识库统计
const knowledgeStats = ref({
  totalDocuments: 0,
  processingDocuments: 0,
  processedDocuments: 0,
  failedDocuments: 0,
  totalStorageSize: 0,
  totalVectorCount: 0
})

const kbRules = {
  name: [
    { required: true, message: '请输入知识库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '长度不超过 200 个字符', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-'
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

// 加载知识库统计
const loadKnowledgeStats = async () => {
  try {
    const response = await api.get('/api/knowledge/stats');
    knowledgeStats.value = response.data
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取知识库列表
const fetchKnowledgeBases = async () => {
  loading.value = true
  try {
    const response = await api.get('/api/knowledge/bases');
    knowledgeBases.value = response.data
  } catch (error) {
    ElMessage.error('获取知识库列表失败！')
    console.error('获取知识库列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 显示新建对话框
const showCreateDialog = () => {
  isEditMode.value = false
  Object.assign(currentKnowledgeBase, {
    id: null,
    name: '',
    description: '',
    userId: 1 // 重置用户ID
  })
  if (kbFormRef.value) {
    kbFormRef.value.resetFields()
  }
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (kb) => {
  isEditMode.value = true
  Object.assign(currentKnowledgeBase, kb) // 复制当前知识库数据
  if (kbFormRef.value) {
    kbFormRef.value.clearValidate()
  }
  dialogVisible.value = true
}

// 提交表单（创建或更新）
const handleSubmit = async () => {
  if (!kbFormRef.value) return
  
  try {
    await kbFormRef.value.validate()
    submitLoading.value = true


    if (isEditMode.value) {
      // 更新知识库
      await api.put(`/api/knowledge/bases/${currentKnowledgeBase.id}`, currentKnowledgeBase);
      ElMessage.success('知识库更新成功！');
    } else {
      // 创建知识库
      await api.post('/api/knowledge/bases', currentKnowledgeBase);
      ElMessage.success('知识库创建成功！');
    }
    dialogVisible.value = false;
    fetchKnowledgeBases(); // 刷新列表
  } catch (error) {
    const errorMessage = error.response?.data?.message || '操作失败，请重试'
    ElMessage.error(errorMessage)
    console.error('知识库操作失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 删除知识库
const deleteKnowledgeBase = async (id) => {
  ElMessageBox.confirm(
    '此操作将永久删除该知识库及其关联的所有文档，是否继续？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await api.delete(`/api/knowledge/bases/${id}`);
        ElMessage.success('知识库删除成功！');
        fetchKnowledgeBases(); // 刷新列表
      } catch (error) {
        const errorMessage = error.response?.data?.message || '删除失败，请重试'
        ElMessage.error(errorMessage)
        console.error('删除知识库失败:', error)
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 查看知识库文档
const viewKnowledgeBaseDocuments = (id) => {
  router.push({ name: 'KnowledgeBaseDocuments', params: { knowledgeBaseId: id } });
}

onMounted(() => {
  
  // 组件挂载时直接加载知识库列表和统计
  fetchKnowledgeBases();
  loadKnowledgeStats();
});

// 监听路由变化，当从子路由返回父路由时重新加载数据
// 不再需要这个监听器，因为父组件不再直接渲染子路由
// watch(() => router.currentRoute.value.name, (newName) => {
//   if (newName === 'KnowledgeBaseManagement') {
//     fetchKnowledgeBases();
//     loadKnowledgeStats();
//   }
// });
</script>

<style scoped>
.knowledge-base-management-container {
  flex: 1; /* 让容器填充可用空间 */
  display: flex; /* 使用 Flexbox 布局 */
  flex-direction: column; /* 垂直堆叠内容 */
  padding: 20px; /* 内部填充 */
  background-color: #f5f7fa; /* 与 Dashboard 的主内容背景色保持一致 */
  overflow: hidden; /* 防止内容溢出 */
  box-sizing: border-box; /* 边框和内边距计算在元素的总宽度和高度内 */
}

.stats {
  display: flex;
  justify-content: space-around;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap; /* 允许统计卡片换行 */
}

.stat-card {
  flex: 1;
  min-width: 180px; /* 确保卡片有最小宽度 */
  max-width: 250px; /* 限制卡片最大宽度 */
  text-align: center;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.stat-item {
  padding: 10px 0;
}

.stat-number {
  font-size: 2em;
  font-weight: bold;
  color: #409eff; /* Element Plus Primary color */
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9em;
  color: #606266;
}

.box-card {
  margin-bottom: 20px;
  flex: 1; /* 让卡片填充剩余空间 */
  display: flex; /* 内部也使用 Flexbox */
  flex-direction: column;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.box-card :deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.box-card :deep(.el-card__body) {
  padding: 0px 20px 20px 20px;
  flex: 1; /* 让 body 填充剩余空间 */
  display: flex; /* 内部也使用 Flexbox */
  flex-direction: column;
}

/* 确保表格高度正确并可滚动 */
.el-table {
  flex: 1; /* 让表格填充可用空间 */
  overflow-y: auto; /* 当内容超出时显示滚动条 */
}

/* Dialog 样式 */
.dialog-footer button:first-child {
  margin-right: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats {
    flex-direction: column;
    align-items: center;
  }

  .stat-card {
    max-width: 90%;
    width: 100%;
  }
}
</style> 